/******************************************************************
 * Copyright @ 2023 广州牛师帮科技文化有限公司. All rights reserverd.
 * @file   src\hooks\useLoginInfo.ts
 * @author 朱剑豪
 * @date   2023/10/11 14:52
 * @desc   登录信息的对接与获取
 ******************************************************************/

import { SSOLoginInfo, SSOUserInfo } from "@nsb/user-center-sso-plugin";
import __localforage from "localforage";
import { del_forage_item, set_forage_item, useLocalForageItem } from "./useLocalForage";

type TItemKey = Exclude<keyof SSOLoginInfo, 'department' | 'position'> | 'departmentId' | 'departmentName' | 'positionId' | 'positionName'
type StringInfo = Omit<SSOLoginInfo, 'permissions' | 'position' | 'department' | 'extensionNo' | 'roleList'>

export const login_forage = __localforage.createInstance({ name: 'default_forage', storeName: 'login_info' })

export const handleLoginInfoItem = (info: StringInfo, key: keyof StringInfo) => {
  const item = info[key]
  if (!item) return;
  const { value } = item
  set_forage_item(login_forage, key, value);
}

export const handleLoginInfo = (info: SSOLoginInfo) => {
  handleLoginInfoItem(info, 'name');
  handleLoginInfoItem(info, 'orgId');
  handleLoginInfoItem(info, 'ticket');
  handleLoginInfoItem(info, 'token');
  handleLoginInfoItem(info, 'userId');
  handleLoginInfoItem(info, 'mobile');
  const { department, position } = info;
  if (department) {
    const { value } = department
    set_forage_item(login_forage, 'departmentId', value.id);
    set_forage_item(login_forage, 'departmentName', '' + value.name);
  }
  if (position) {
    const { value } = position
    set_forage_item(login_forage, 'positionId', value.id);
    set_forage_item(login_forage, 'positionName', '' + value.name);
  }
  if (info.permissions) {
    const { value } = info.permissions;
    set_forage_item(login_forage, 'permissions', value);
  }
}
export function clearLoginInfo() {
  del_forage_item(login_forage, 'name');
  del_forage_item(login_forage, 'orgId');
  del_forage_item(login_forage, 'ticket');
  del_forage_item(login_forage, 'token');
  del_forage_item(login_forage, 'userId');
  del_forage_item(login_forage, 'mobile');
  del_forage_item(login_forage, 'permissions')
  del_forage_item(login_forage, 'positionId')
  del_forage_item(login_forage, 'positionName')
  del_forage_item(login_forage, 'departmentId')
  del_forage_item(login_forage, 'departmentName')


  /*
  TODO: 
    目前登出后直接清理全部数据。
    也许有一天需要根据条件保留某些数据
    -Gim
  */
  localStorage.clear();
  sessionStorage.clear();
}
export function getLoginInfo(key: TItemKey): Promise<string | null> {
  return login_forage.getItem(key);
}
export function useLoginInfo<T = any>(key: string): T | null {
  const [value] = useLocalForageItem<T>({ key, ...login_forage.config(), storage: login_forage })
  return value
}